export default {
  namespaced: true,
  state: {
    goodsList: uni.getStorageSync('cart') || []
  },
  getters: {
    getCartList (state) {
      return state.goodsList
    },
    // 获取总数量
    getTotal (state) {
      let total = 0
      state.goodsList.forEach(item => {
        total += item.goods_number
      })

      return total
    },
    // 获取选中的数量
    getSelectTotal (state) {
      let total = 0
      state.goodsList.forEach(item => {
        if (item.goods_state) {
          total += item.goods_number
        }
      })

      return total
    },
    // 获取总价格
    getSelectAmount (state) {
      let amount = 0
      state.goodsList.forEach(item => {
        if (item.goods_state) {
          amount += item.goods_number * item.goods_price
        }
      })

      return amount
    },
    isAllCheck (state) {
      let isAllCheck = true
      state.goodsList.forEach(item => {
        if (!item.goods_state) {
          isAllCheck = false
        }
      })

      return isAllCheck
    }
  },
  mutations: {
    addToCart (state, goods) {
      const findGoods = state.goodsList.find(
        item => item.goods_id === goods.goods_id
      )
      // 如果购物车中之前存在，则把数量累加
      if (findGoods) {
        findGoods.goods_number += goods.goods_number
      } else {
        state.goodsList.push(goods)
      }

      // 保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    // 更改商品状态
    updateGoodsState (state, goods) {
      const findGoods = state.goodsList.find(
        item => item.goods_id === goods.goods_id
      )
      if (findGoods) {
        findGoods.goods_state = goods.goods_state
      }

      // 保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    updateGoodsNumber (state, goods) {
      const findGoods = state.goodsList.find(
        item => item.goods_id === goods.goods_id
      )
      if (findGoods) {
        findGoods.goods_number = goods.goods_number
      }

      // 保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    // 根据id删除
    deleteGoodsById (state, goods_id) {
      // const findIndex = state.goodsList.findIndex(
      //   item => item.goods_id === goods_id
      // )
      // if (findIndex > -1) {
      //   state.goodsList.splice(findIndex, 1)
      // }

      state.goodsList = state.goodsList.filter(
        item => item.goods_id !== goods_id
      )

      // 保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    // 全选&反选
    updateAllGoodsState (state, goods_state) {
      state.goodsList.forEach(item => {
        item.goods_state = goods_state
      })

      // 保存到本地
      uni.setStorageSync('cart', state.goodsList)
    }
  }
}
